package org.example;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    int getLen(ListNode head) {
        int len = 0;
        while (head != null) {
            len++;
            head = head.next;
        }
        return len;
    }

    ListNode reverse(ListNode head, int limit) {
        if (head == null) {
            return null;
        }
        ListNode cur = head;
        ListNode prev = null;
        ListNode child = cur.next;
        int count = 0;
        while (child != null) {
            cur.next = prev;
            count++;
            if (count == limit) {
                break;
            }
            prev = cur;
            cur = child;
            child = child.next;
        }
        return cur;
    }

    public boolean isPalindrome(ListNode head) {
        int len = getLen(head);
        if (len <= 1) {
            return true;
        }
        ListNode right = head;
        for (int i = 1; i <= len / 2; i++) {
            right = right.next;
        }
        if (len % 2 == 1) {
            right = right.next;
        }
        ListNode left = reverse(head, len / 2);
        while (left != null) {
            if (left.val != right.val) {
                return false;
            }
            left = left.next;
            right = right.next;
        }
        return true;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}